package easytasks.ui;

import easytasks.data.TaskCategory;
import easytasks.main.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.widget.EditText;

public class NewTaskCategoryNameDialog
{
	AlertDialog.Builder builder;
	private AlertDialog dialog;
	
	private EditText editNewName;
	private TaskCategory oldValue;
	private TaskCategory newValue = null;
	
	private DialogInterface.OnClickListener onOkClickHandler;
	
	public NewTaskCategoryNameDialog(Context context, TaskCategory oldValue) 
	{
		if (context == null) throw new IllegalArgumentException("'context' must be not null.");
		setOldValue(oldValue);
		
		builder = new AlertDialog.Builder(context);
		
		builder.setTitle(context.getResources().getString(R.string.edittaskcategories_edit_title) + " \"" + oldValue.getName() + "\"");	
		builder.setMessage(R.string.edittaskcategories_edit_message);
		
		editNewName = new EditText(context);
		editNewName.setInputType(InputType.TYPE_CLASS_TEXT);
		editNewName.setFilters(new InputFilter[]{new InputFilter.LengthFilter(30)});
		builder.setView(editNewName);
		
		builder.setPositiveButton(R.string.edittask_ok, new DialogInterface.OnClickListener() {					
			public void onClick(DialogInterface dialog, int which)
			{
				newValue = new TaskCategory(editNewName.getText().toString().trim());
				if (NewTaskCategoryNameDialog.this.onOkClickHandler != null) NewTaskCategoryNameDialog.this.onOkClickHandler.onClick(dialog, which);
			}
		});

		builder.setNegativeButton(R.string.edittask_cancel, null);
		
		editNewName.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			public void afterTextChanged(Editable s)
			{
				refresh();
			}
		});
		
		dialog = builder.create();
	}
	
	public void setOnOkClickHandler(DialogInterface.OnClickListener onOkClickHandler)
	{
		this.onOkClickHandler = onOkClickHandler;
	}
	
	private void setOldValue(TaskCategory oldValue)
	{
		if (oldValue == null) throw new IllegalArgumentException("'value' must be not null.");
		this.oldValue = oldValue;
	}
	
	private void refresh()
	{
		String name = editNewName.getText().toString().trim().toLowerCase();
		boolean cond1 = !name.equals("");
		boolean cond2 = !name.equals(oldValue.getName().toLowerCase());
		
		dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(cond1 && cond2);
	}

	public void show()
	{
		dialog.show();
		refresh();
	}
	
	public TaskCategory getNewValue()
	{
		return newValue;
	}
}
